<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>题库导入工具</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 30px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: #2c5aa0;
        }
        .upload-area {
            border: 2px dashed #2c5aa0;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            background-color: #f0f4f8;
        }
        .file-input {
            display: none;
        }
        .btn {
            background: linear-gradient(135deg, #2c5aa0 0%, #1e3a8a 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px;
        }
        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .btn.success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        .format-guide {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .manual-input {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
        }
        .input-row {
            display: grid;
            grid-template-columns: 1fr 1fr 3fr 1fr 1fr 1fr 1fr 1fr 2fr;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
        }
        .input-row input, .input-row select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .input-row label {
            font-weight: bold;
            font-size: 12px;
            text-align: center;
        }
        .output-area {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
        .question-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 10px;
            margin: 10px 0;
        }
        .question-item {
            background: white;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
        }
        .remove-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        .status-message {
            padding: 10px;
            border-radius: 6px;
            margin: 10px 0;
            text-align: center;
            font-weight: bold;
        }
        .status-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>题库导入工具</h1>
            <p>手动输入题目，直接保存到题库</p>
        </div>

        <div class="format-guide">
            <h3>使用说明：</h3>
            <p>1. 在下方表单中填写题目信息</p>
            <p>2. 点击"添加题目"按钮添加每道题</p>
            <p>3. 在题目列表中查看已添加的题目</p>
            <p>4. 点击"保存到题库"直接将题目保存到data.js文件中</p>
            <p><strong>注意：保存后题目将立即在主页面中可用！</strong></p>
        </div>

        <div class="manual-input">
            <h3>添加新题目：</h3>
            <div class="input-row">
                <label>题型</label>
                <label>学科</label>
                <label>题目内容</label>
                <label>选项A</label>
                <label>选项B</label>
                <label>选项C</label>
                <label>选项D</label>
                <label>正确答案</label>
                <label>解析说明</label>
            </div>
            <div class="input-row">
                <select id="questionType">
                    <option value="single">单选题</option>
                    <option value="multiple">多选题</option>
                    <option value="judge">判断题</option>
                </select>
                <select id="questionSubject">
                    <option value="math">数学</option>
                    <option value="chinese">语文</option>
                    <option value="english">英语</option>
                    <option value="science">科学</option>
                </select>
                <input type="text" id="questionText" placeholder="请输入题目内容">
                <input type="text" id="optionA" placeholder="选项A">
                <input type="text" id="optionB" placeholder="选项B">
                <input type="text" id="optionC" placeholder="选项C">
                <input type="text" id="optionD" placeholder="选项D">
                <input type="text" id="correctAnswer" placeholder="A 或 A,C">
                <input type="text" id="explanation" placeholder="答案解析">
            </div>
            <div style="text-align: center; margin-top: 15px;">
                <button class="btn" onclick="addQuestion()">添加题目</button>
                <button class="btn" onclick="clearForm()">清空表单</button>
            </div>
        </div>

        <div class="question-list" id="questionList" style="display: none;">
            <h3>已添加的题目：</h3>
            <div id="questionItems"></div>
        </div>

        <div style="text-align: center; margin-top: 20px;">
            <button class="btn success" onclick="saveToDatabase()" id="saveBtn" style="display: none;">保存到题库</button>
            <button class="btn" onclick="clearAllQuestions()" id="clearBtn" style="display: none;">清空所有题目</button>
        </div>

        <div id="statusMessage"></div>
    </div>

    <script src="data.js"></script>
    <script>
        let questions = [];
        let nextId = getNextAvailableId();

        function getNextAvailableId() {
            // Get the highest ID from existing questions and add 1
            if (typeof questionDatabase !== 'undefined' && questionDatabase.length > 0) {
                const maxId = Math.max(...questionDatabase.map(q => q.id));
                return maxId + 1;
            }
            return 16; // Default starting ID
        }

        function addQuestion() {
            const type = document.getElementById('questionType').value;
            const subject = document.getElementById('questionSubject').value;
            const questionText = document.getElementById('questionText').value.trim();
            const optionA = document.getElementById('optionA').value.trim();
            const optionB = document.getElementById('optionB').value.trim();
            const optionC = document.getElementById('optionC').value.trim();
            const optionD = document.getElementById('optionD').value.trim();
            const answerText = document.getElementById('correctAnswer').value.trim().toUpperCase();
            const explanation = document.getElementById('explanation').value.trim();

            // Validation
            if (!questionText) {
                showStatus('请输入题目内容', 'error');
                return;
            }

            // Prepare options based on question type
            let options = [];
            if (type === 'judge') {
                options = ['正确', '错误'];
            } else {
                if (optionA) options.push(optionA);
                if (optionB) options.push(optionB);
                if (optionC) options.push(optionC);
                if (optionD) options.push(optionD);
                
                if (options.length < 2) {
                    showStatus('请至少提供2个选项', 'error');
                    return;
                }
            }

            // Parse correct answer
            let correctAnswer;
            if (type === 'multiple') {
                correctAnswer = [];
                if (answerText.includes(',')) {
                    answerText.split(',').forEach(a => {
                        const index = a.trim().charCodeAt(0) - 65;
                        if (index >= 0 && index < options.length) {
                            correctAnswer.push(index);
                        }
                    });
                } else {
                    for (let char of answerText) {
                        const index = char.charCodeAt(0) - 65;
                        if (index >= 0 && index < options.length) {
                            correctAnswer.push(index);
                        }
                    }
                }
                if (correctAnswer.length === 0) correctAnswer = [0];
            } else {
                const index = answerText.charCodeAt(0) - 65;
                correctAnswer = (index >= 0 && index < options.length) ? index : 0;
            }

            // Create question object
            const question = {
                id: nextId++,
                type: type,
                subject: subject,
                question: questionText,
                options: options,
                correctAnswer: correctAnswer,
                explanation: explanation || 'No explanation provided'
            };

            questions.push(question);
            updateQuestionList();
            clearForm();
            showStatus('题目添加成功！', 'success');
        }

        function updateQuestionList() {
            const listContainer = document.getElementById('questionList');
            const itemsContainer = document.getElementById('questionItems');
            
            if (questions.length === 0) {
                listContainer.style.display = 'none';
                document.getElementById('saveBtn').style.display = 'none';
                document.getElementById('clearBtn').style.display = 'none';
                return;
            }

            listContainer.style.display = 'block';
            document.getElementById('saveBtn').style.display = 'inline-block';
            document.getElementById('clearBtn').style.display = 'inline-block';

            itemsContainer.innerHTML = '';
            questions.forEach((q, index) => {
                const typeText = q.type === 'single' ? '单选题' : q.type === 'multiple' ? '多选题' : '判断题';
                const subjectText = q.subject === 'math' ? '数学' : q.subject === 'chinese' ? '语文' : q.subject === 'english' ? '英语' : '科学';
                
                const div = document.createElement('div');
                div.className = 'question-item';
                div.innerHTML = `
                    <strong>题目${q.id}:</strong> ${q.question}<br>
                    <strong>类型:</strong> ${typeText} | <strong>学科:</strong> ${subjectText}<br>
                    <strong>选项:</strong> ${q.options.join(', ')}<br>
                    <strong>答案:</strong> ${Array.isArray(q.correctAnswer) ? 
                        q.correctAnswer.map(i => String.fromCharCode(65 + i)).join(',') : 
                        String.fromCharCode(65 + q.correctAnswer)}<br>
                    <strong>解析:</strong> ${q.explanation}<br>
                    <button class="remove-btn" onclick="removeQuestion(${index})">删除</button>
                `;
                itemsContainer.appendChild(div);
            });
        }

        function removeQuestion(index) {
            if (confirm('确定要删除这道题目吗？')) {
                questions.splice(index, 1);
                updateQuestionList();
            }
        }

        function clearForm() {
            document.getElementById('questionText').value = '';
            document.getElementById('optionA').value = '';
            document.getElementById('optionB').value = '';
            document.getElementById('optionC').value = '';
            document.getElementById('optionD').value = '';
            document.getElementById('correctAnswer').value = '';
            document.getElementById('explanation').value = '';
        }

        function clearAllQuestions() {
            if (confirm('确定要清空所有题目吗？')) {
                questions = [];
                nextId = getNextAvailableId();
                updateQuestionList();
                showStatus('', '');
            }
        }

        function saveToDatabase() {
            if (questions.length === 0) {
                showStatus('请先添加一些题目', 'error');
                return;
            }

            try {
                // Combine existing questions with new questions
                const allQuestions = [...questionDatabase, ...questions];
                
                // Generate the complete data.js file content
                let code = `// Question database\nconst questionDatabase = [\n`;
                
                allQuestions.forEach((q, index) => {
                    code += `    {\n`;
                    code += `        id: ${q.id},\n`;
                    code += `        type: '${q.type}',\n`;
                    code += `        subject: '${q.subject}',\n`;
                    code += `        question: '${q.question.replace(/'/g, "\\'")}',\n`;
                    code += `        options: [${q.options.map(opt => `'${opt.replace(/'/g, "\\'")}'`).join(', ')}],\n`;
                    code += `        correctAnswer: ${Array.isArray(q.correctAnswer) ? `[${q.correctAnswer.join(', ')}]` : q.correctAnswer},\n`;
                    code += `        explanation: '${q.explanation.replace(/'/g, "\\'")}'`;
                    code += `\n    }`;
                    if (index < allQuestions.length - 1) code += ',';
                    code += `\n`;
                });
                
                code += `];\n\n`;
                code += `// Export for use in other files\n`;
                code += `if (typeof module !== 'undefined' && module.exports) {\n`;
                code += `    module.exports = questionDatabase;\n`;
                code += `}`;

                // Create and download the updated data.js file
                const blob = new Blob([code], { type: 'text/javascript' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'data.js';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);

                showStatus(`成功保存${questions.length}道题目到题库！请将下载的data.js文件替换原文件。`, 'success');
                
                // Clear the questions after successful save
                questions = [];
                nextId = getNextAvailableId();
                updateQuestionList();
                
            } catch (error) {
                showStatus('保存失败：' + error.message, 'error');
            }
        }

        function showStatus(message, type) {
            const statusDiv = document.getElementById('statusMessage');
            if (!message) {
                statusDiv.innerHTML = '';
                return;
            }
            
            statusDiv.innerHTML = `<div class="status-message status-${type}">${message}</div>`;
            
            // Auto-hide success messages after 5 seconds
            if (type === 'success') {
                setTimeout(() => {
                    statusDiv.innerHTML = '';
                }, 5000);
            }
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Question import tool loaded successfully');
            nextId = getNextAvailableId();
        });
    </script>
</body>
</html>